<?php
/**
 * Created by PhpStorm.
 * User: lixy
 * Date: 2016/1/19
 * Time: 13:16
 */

namespace app\controllers;

use app\models\weixin\T_WXMALL_DORACARD;
use app\models\weixin\T_WXMALL_USER;
use Yii;
use app\lib\WXBaseController;
use app\lib\WebService;

;
use app\models\HomeDao;
use app\lib\WeixinUtils;
use app\models\BizDao;
use app\models\T_WX_PAY_LOG;

class WxHomeController extends WXBaseController
{


    //送礼记录列表
    public function actionSendRecord()
    {
        self::__validUser();
        return $this->render("send-record", []);
    }

//json 返回送礼记录   get-send-record-handle
    public function actionGetSendRecordHandle()
    {
        $session = Yii::$app->session;
        $usereid = $session->get(static::sessionKey)->userid;

        $request = Yii::$app->request;
        $start = $request->post("start");
        $pagesize = $request->post("pagesize");

        $status = $request->post("status");
        $type = $request->post("type");

        $begintime = $request->post("begintime");
        $endtime = $request->post("endtime");
        $msg = "";

        $flag = 1;
        $rlist = HomeDao::getSendRecordList($usereid, $start, $pagesize, $type, $status, $begintime, $endtime);
        foreach ($rlist as &$myCard) {
            $myCard['CREATE_DATETIME_SHOW'] = date("m-d", strtotime($myCard['CREATE_DATETIME']));
        }
        echo json_encode(['msg' => $msg, 'flag' => $flag, 'rlist' => $rlist]);
    }

    //收礼记录列表
    public function actionReceiveRecord($status = 0)
    {
        self::__validUser();

        return $this->render("receive-record", []);
    }

    //json 返回收礼记录   get-receive-record-handle
    public function actionGetReceiveRecordHandle()
    {
        $session = Yii::$app->session;
        $usereid = $session->get(static::sessionKey)->userid;

        $request = Yii::$app->request;
        $start = $request->post("start");
        $pagesize = $request->post("pagesize");

        $status = $request->post("status");
        $type = $request->post("type");

        $begintime = $request->post("begintime");
        $endtime = $request->post("endtime");
        $msg = "";

        $flag = 1;
        $rlist = HomeDao::getReceiveRecordList($usereid, $start, $pagesize, $type, $status, $begintime, $endtime);
        foreach ($rlist as &$myCard) {
            $myCard['CREATE_DATETIME_SHOW'] = date("m-d", strtotime($myCard['CREATE_DATETIME']));
        }
        echo json_encode(['msg' => $msg, 'flag' => $flag, 'rlist' => $rlist]);
    }

    public function actionHome()
    {

        $banners = HomeDao::get_Home_banner();
        $cell5 = HomeDao::get_Home_5cell();
        $goods3 = HomeDao::get_Home_3goods();
        $newgoods = HomeDao::get_Home_newgoods();
        return $this->render("home", ['banners' => $banners, 'cell5' => $cell5, 'goods3' => $goods3, 'newgoods' => $newgoods]);
    }

    public function actionViewWlxx($orderNo, $giftCode)
    {
        //查询nc
        //测试用  $good['GOODS_CODE']
        // array('orderNo'=>'D_0-2740_1451270408554','giftCode'=>'DLHCJ0037');
//        $ncwlxx=WebService::nc_getWlxxByWzOrder('D_0-2740_1451270408554','DLHCJ0037');
        $ncwlxx = WebService::nc_getWlxxByWzOrder($orderNo, $giftCode);
        return $this->render("view-wlxx", ['ncwlxx' => $ncwlxx, 'giftCode' => $giftCode]);
    }

    //json 兑换朵拉币   receive-dora-coin-handle
    public function actionReceiveDoraCoinHandle()
    {
        self::__validUser(true);
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        $usereid = $session->get(static::sessionKey)->userid;

        $type_id = $request->post("type_id");
        $order_id = $request->post("order_id");
        $exchange_id = $request->post("exchange_id");

        $msg = "";
        $flag = 0;
        if ($type_id == '1') { //如果是离线的，写入user_id,收卡;
            if (T_WXMALL_DORACARD::isOfflineCard($exchange_id)) {
                if (T_WXMALL_DORACARD::isReceive_card_offline($exchange_id) == false) {
                    $re = T_WXMALL_DORACARD::P_RECEIVE_CARD_OFFLINE($exchange_id, $usereid);
                    if ($re != '1') {
                        echo $re;
                        exit;
                    }

                }
            }
        }


        $re = HomeDao::P_RECEIVE_DORACOIN($usereid, $type_id, $order_id, $exchange_id);
        if ($re == '1') {
            $flag = 1;
        } else {
            $msg = "兑换失败";
        }


        echo json_encode(['msg' => $msg, 'flag' => $flag, 're' => $re]);
    }

    //扣除朵拉币 cash-dora-coin-handle
    public function actionCashDoraCoinHandle()
    {
        self::__validUser(true);
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        $usereid = $session->get(static::sessionKey)->userid;

        $order_code = $request->post("order_code");
        $current_coin = $request->post("current_coin");

        $msg = "";
        $flag = 0;
        $re = BizDao::P_WXMALL_CASH_COIN($usereid, $current_coin, $order_code);


        if ($re == '1') {
            $flag = 1;
            $realPrice = $request->post("realPrice");;
            //模拟调用微信回调--支付成功
            if (YII_ENV == 'dev' && $realPrice != '0') {
                $openid = $session->get(static::sessionKey)->openid;

                $attach = '';
                if ($current_coin != '0') {
                    $attach = "current_coin:{$current_coin};";
                }
                $attach = $attach . "order_no:{$order_code};";
                $type = substr($order_code, 0, 2);

                if ($type == 'WD') {//card
                    T_WX_PAY_LOG::write_P_WXMALL_PAY_ORDER('SUCCESS', 'dev'
                        , $openid, $realPrice, $order_code, 'weixin-order-code', date("YmdHis")
                        , $attach);
                }
                if ($type == 'WP') {//bag
                    $re = T_WX_PAY_LOG::P_WXMALL_PAY_DORABAG_ORDER('SUCCESS', 'dev'
                        , $openid, $realPrice, $order_code, 'weixin-order-code', date("YmdHis")
                        , $attach);
                }
                if ($type == 'SP') {//goods
                    $re = T_WX_PAY_LOG::P_WXMALL_PAY_GOODS('SUCCESS', 'dev'
                        , $openid, $realPrice, $order_code, 'weixin-order-code', date("YmdHis")
                        , $attach);
                }
            }
        } else {
            $msg = $re;
        }


        echo json_encode(['msg' => $msg, 'flag' => $flag, 're' => $re]);
    }

    public function actionInvoiceForm($object_type, $object_id)
    {

        $session = Yii::$app->session;

        $invoice_content_types = HomeDao::get_dict_list("invoice_content_type");
        //查询已有发票信息
        $invoice = HomeDao::get_t_wxmall_invoice($object_type, $object_id);

        return $this->render("invoice-form", ['invoice_content_types' => $invoice_content_types
            , 'invoice' => $invoice, 'object_type' => $object_type, 'object_id' => $object_id]);
    }

    //发票运费
    Const  invoice_FREIGHT = 8;

    //json 提交发票信息   submit-invoice-handle
    public function actionSubmitInvoiceHandle()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $msg = "";
        $flag = 0;
        $usereid = $session->get(static::sessionKey)->userid;
        $object_type = $request->post("object_type");
        $object_id = $request->post("object_id");

        $DTYPE = $request->post("DTYPE");
        $DINVOICE_TITLE = $request->post("DINVOICE_TITLE");
        $DRECEIVER_NAME = $request->post("DRECEIVER_NAME");
        $DRECEIVER_PHONE = $request->post("DRECEIVER_PHONE");
        $DRECEIVER_ADDRESS = $request->post("DRECEIVER_ADDRESS");
        $DREMARK = $request->post("DREMARK");
        if ($DTYPE == '1' || $DTYPE == '2') {//增值税发票是否加运费？？收件人信息是否填写？？  存储过程有问题
            $DFREIGHT = static::invoice_FREIGHT;
        } else {
            $DFREIGHT = 0;
        }
        $DCONTENT_TYPE = $request->post("DCONTENT_TYPE");
        //校验是否可以修改发票信息
        if ($object_type == '2') {
            $re = HomeDao::verifyBagOrderCode($object_id, $usereid);
            if ($re == 0) {
                $msg = "查不到此订单";
                echo json_encode(['msg' => $msg, 'flag' => $flag]);
                exit;
            }
        }


        //提交发票信息
        $re = HomeDao::P_WXMALL_INVOICE_DETAIL($object_type, $object_id, $DTYPE, $DINVOICE_TITLE, $DRECEIVER_NAME, $DRECEIVER_PHONE, $DRECEIVER_ADDRESS, $DREMARK, $DFREIGHT, $DCONTENT_TYPE);

        if ($re == '1') {
            $flag = 1;
        } else {
            $msg = $re;
        }
        echo json_encode(['msg' => $msg, 'flag' => $flag]);
    }

    // 获取朵拉币记录 doracoin-record
    public function actionDoracoinRecord()
    {
        static::__validUser();
        $session = Yii::$app->session;
        $usereid = $session->get(static::sessionKey)->userid;

        $doracoinList = HomeDao::get_DoracoinRecord($usereid);
        $totalDoracoin = 0;
        foreach ($doracoinList as $doracoin) {
            $totalDoracoin += $doracoin["DORACOIN"];
        }

        $userHeaderImg = $session->get(static::sessionKey)->headimgurl;
        return $this->render("doracoin-record", ['doracoin_list' => $doracoinList, 'user_header_img' => $userHeaderImg, 'total_doracoin' => $totalDoracoin]);
    }

    public function actionVoucherExchangeUser()
    {
        return $this->render("voucher-exchange-user", []);
    }

    //兑换线下卡voucher-exchange?card_voucher=00000001&card_token=02300001
    public function actionVoucherExchange($card_voucher, $card_token)
    {

        $re = T_WXMALL_DORACARD::get_t_wxmall_doracard_voucher($card_voucher, $card_token);
        if (count($re) == 0) {
            static::dump_info('兑换码错误');

        }
        $re = $re[0];
        $card_code_id = $re['ORDER_CODE_ID'];
        if (T_WXMALL_DORACARD::isReceive_card_offline($card_code_id)) {
            static::dump_info('兑换码已经使用');
        }
        return $this->redirect(['wx-biz/good-chose', 'id' => $card_code_id]);
    }

    // 合作咨询
    public function actionContacts()
    {
        return $this->render('contacts');
    }

    public function actionAboutDorabox()
    {
        return $this->render('about-dorabox');
    }


    //个人中心
    public function actionPersonalCenter()
    {
        static::__validUser();
        $currentUserId = static::getSessionUserid();
        $user_info = T_WXMALL_USER::getUserByUserid($currentUserId);
        $user_info = $user_info[0];

        return $this->render('personal-center', ['user_info' => $user_info]);
    }

//地址管理 address-management
    public function actionAddressManagement($backurl = '')
    {
        static::__validUser();

        $addressList = HomeDao::getUserAddressList(self::getSessionUserid());

        return $this->render('address-management', [
            'addressList' => $addressList,
            'backurl' => $backurl,
        ]);
    }

    //地址增加或者编辑
    public function actionAddressEdit($aid = '',$backurl = '')
    {
        static::__validUser();
        $address = [];
        if ($aid != '') {
            $address = HomeDao::getAddress($aid, self::getSessionUserid());
        }
        return $this->render('address-edit', [
            'aid' => $aid,
            'address' => $address,
            'backurl' => $backurl,
        ]);
    }

    //删除地址 del-address-handle
    public function actionDelAddressHandle()
    {
        $id = static::getRequestPost("id");
        $re = HomeDao::delAddress($id,self::getSessionUserid());

        if ($re == false) {
            return $this->renderJson(null, 1, '删除地址失败');
        }
        return $this->renderJson(null);
    }
    //设置默认地址 set-address-default-handle
    public function actionSetAddressDefaultHandle()
    {
        $id = static::getRequestPost("id");
        $re = HomeDao::setAddressDefault($id,self::getSessionUserid());

        if ($re == false) {
            return $this->renderJson(null, 1, '设置默认地址失败');
        }
        return $this->renderJson(null);
    }
    /**
     * get-area-handle
     * 获得地区三级体系
     */
    public function actionGetAreaHandle()
    {
        $parent_id = static::getRequestPost("parent_id");

        if ($parent_id == null) {
            $others = HomeDao::getAreaList_sheng();
        } else {
            $others = HomeDao::getAreaList_other($parent_id);
        }

        return $this->renderJson(['others' => $others]);
    }

    /**
     * 保存收货地址
     * save-user-address-handle
     */
    public function actionSaveUserAddressHandle()
    {
        $msg = "";

        $userid = static::getSessionUserid();
        $id = static::getRequestPost("id");
        $rece_name = static::getRequestPost("rece_name");
        $rece_phone = static::getRequestPost("rece_phone");
        $rece_address = static::getRequestPost("rece_address");
        $sheng = static::getRequestPost("sheng");
        $shi = static::getRequestPost("shi");
        $qu = static::getRequestPost("qu");

        //保存用户收货地址信息
        $re = HomeDao::saveReceiverAddress($id, $userid, $rece_name, $rece_phone, $rece_address, $sheng, $shi, $qu);

        if ($re) {
            $status = 0;
        } else {
            $msg = "地址保存失败";
            $status = 1;
        }
        return $this->renderJson(null, $status, $msg);
    }
}